package ren.nearby.http.base;

import android.annotation.TargetApi;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.util.Log;

import com.facebook.stetho.Stetho;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.FormatStrategy;
import com.orhanobut.logger.Logger;
import com.orhanobut.logger.PrettyFormatStrategy;

import com.tencent.smtt.sdk.QbSdk;
import com.tencent.tinker.entry.DefaultApplicationLike;


import me.drakeet.library.CrashWoodpecker;
import me.drakeet.library.PatchMode;
import ren.nearby.http.base.tinker.DiBaseApplication;
import ren.nearby.http.di.HttpModule3;

import ren.nearby.http.moduledi.DaggerDiComponent;
import ren.nearby.http.moduledi.DiComponent;


/**
 * Created by Administrator on 2018/4/26 0026.
 */


public class BaseApplicationLike extends DefaultApplicationLike {


    public BaseApplicationLike(
            Application application,
            int tinkerFlags,
            boolean tinkerLoadVerifyFlag,
            long applicationStartElapsedTime,
            long applicationStartMillisTime,
            Intent tinkerResultIntent) {
        super(
                application,
                tinkerFlags,
                tinkerLoadVerifyFlag,
                applicationStartElapsedTime,
                applicationStartMillisTime,
                tinkerResultIntent);
    }


    /**
     * install multiDex before install tinker
     * so we don't need to put the tinker lib classes in the main dex
     *
     * @param base
     */
    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    @Override
    public void onBaseContextAttached(Context base) {

        Log.e("rent","BaseApplication - attachBaseContext");
//        https://blog.csdn.net/javazejian/article/details/73413292
        applicationDelegate = new ApplicationDelegate();
        applicationDelegate.attachBaseContext(base);
        //you must install multiDex whatever tinker is installed!
//        MultiDex.install(base);
     /*   SampleApplicationContext.application = getApplication();
        SampleApplicationContext.context = getApplication();

        TinkerManager.setTinkerApplicationLike(this);

        TinkerManager.initFastCrashProtect();
        //should set before tinker is installed
        TinkerManager.setUpgradeRetryEnable(true);

        //optional set logIml, or you can use default debug log
        TinkerInstaller.setLogIml(new MyLogImp());


        TinkerInstaller.install(this);
        Tinker tinker = Tinker.with(getApplication());*/

//        Beta.installTinker(this);
        diComponent =
                DaggerDiComponent
                        .builder()
                        .httpModule3(new HttpModule3(getApplication(), 0))
                        .build();
        applicationDelegate.onCreate((DiBaseApplication) getApplication(), diComponent);

    }
    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public void registerActivityLifecycleCallback(Application.ActivityLifecycleCallbacks callbacks) {
        getApplication().registerActivityLifecycleCallbacks(callbacks);
    }
    private static DiComponent diComponent;

    public DiComponent getDiComponent() {
        return diComponent;
    }

    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public void registerActivityLifecycleCallbacks(Application.ActivityLifecycleCallbacks callback) {
        getApplication().registerActivityLifecycleCallbacks(callback);
    }

    @Override
    public void onCreate() {
        super.onCreate();
//        Bugly.init(getApplication(),"900029763",true);
        initLog();
        initCrash();
        initLeakCanary();
        initStetho();
        initDagger2();
        x5Web();

    }


    private ApplicationDelegate applicationDelegate;

    public void x5Web() {
        //搜集本地tbs内核信息并上报服务器，服务器返回结果决定使用哪个内核。

        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {

            @Override
            public void onViewInitFinished(boolean arg0) {
                // TODO Auto-generated method stub
                //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
                Logger.e(" onViewInitFinished is " + arg0);
            }

            @Override
            public void onCoreInitFinished() {
                // TODO Auto-generated method stub
            }
        };
        //x5内核初始化接口
        QbSdk.initX5Environment(getApplication(), cb);
    }

    /**
     * dagger2注入
     */
    public void initDagger2() {


    }

    /**
     * 网络请求分析
     */
    public void initStetho() {
        Stetho.initializeWithDefaults(getApplication());
        //配置okhttp库的网络请求分析 我们打开Chrome，在地址栏输入chrome://inspect/
        //new OkHttpClient.Builder()
        //.addNetworkInterceptor(new StethoInterceptor())
        //.build()
    }

    /**
     * 内存泄漏检测
     */
    public void initLeakCanary() {
//        if (LeakCanary.isInAnalyzerProcess(this)) {
//            return;
//        }
//        LeakCanary.install(this);
    }

    /**
     * 初始化输出日志配置
     */
    public void initLog() {
        FormatStrategy formatStrategy = PrettyFormatStrategy
                .newBuilder()
                .showThreadInfo(true)
//                .methodCount(5)
//                .methodOffset(7)
//                .logStrategy()
                .tag(getLogTag())
                .build();
        Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy));
    }

    /**
     * 异常处理分析
     */
    public void initCrash() {
        CrashWoodpecker.instance()
                .withKeys("widget", "me.drakeet")
                .setPatchMode(PatchMode.SHOW_LOG_PAGE)
                .setPatchDialogUrlToOpen("https://drakeet.me")
                .setPassToOriginalDefaultHandler(true)
                .flyTo(getApplication());
    }

    private String tag = "NBlock";

    /**
     * 获取log标题
     *
     * @return
     */
    public String getLogTag() {
        return tag;
    }

}
